package com.probiz.estoresf.cart.web.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.probiz.estore.Constants;
import com.probiz.estore.cart.CheckoutConstants;
import com.probiz.estore.cart.util.ShoppingCartUtil;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.cart.Shoppingcart;
import com.probiz.estore.common.model.cart.ShoppingcartItem;
import com.probiz.estore.common.model.customer.Address;
import com.probiz.estore.common.model.customer.ShopPoint;
import com.probiz.estore.common.model.order.CheckoutSession;
import com.probiz.estore.common.model.order.SalesOrder;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.sales.PromoRule;
import com.probiz.estore.common.model.system.PaymentGateway;
import com.probiz.estore.common.model.system.PaymentMethod;
import com.probiz.estore.common.model.system.SelfCollectionCentre;
import com.probiz.estore.common.model.system.Wrap;
import com.probiz.estore.common.service.CheckoutService;
import com.probiz.estore.common.service.CustomerService;
import com.probiz.estore.common.service.OrderService;
import com.probiz.estore.common.service.PromoService;
import com.probiz.estore.common.util.DateUtil;
import com.probiz.estore.core.controller.GenericStoreFrontController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.customer.service.ShopPointManager;
import com.probiz.estore.order.service.SalesOrderManager;
import com.probiz.estore.system.service.PaymentMethodManager;
import com.probiz.estore.system.service.SelfCollectionCentreManager;
import com.probiz.estore.system.service.SystemService;
import com.probiz.estore.webapp.util.RequestContext;
import com.probiz.estore.webapp.util.RequestUtil;

public class CheckoutController extends GenericStoreFrontController {

    private PaymentMethodManager paymentMethodManager;
	
	private CheckoutService checkoutService;
	
	private PromoService promoService; 
	
	private CustomerService customerService;
	
	private SystemService systemService;
	
	private SalesOrderManager salesOrderManager;
	
	private SelfCollectionCentreManager selfCollectionCentreManager;
	
	public void setPaymentMethodManager(PaymentMethodManager paymentMethodManager) {
		this.paymentMethodManager = paymentMethodManager;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public void setPromoService(PromoService promoService) {
		this.promoService = promoService;
	}
	
	
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}
	
	public void setSalesOrderManager(SalesOrderManager salesOrderManager) {
		this.salesOrderManager = salesOrderManager;
	}

	public void setCheckoutService(CheckoutService checkoutService) {
		this.checkoutService = checkoutService;
	}
	
	public void setSelfCollectionCentreManager(SelfCollectionCentreManager selfCollectionCentreManager) {
		this.selfCollectionCentreManager = selfCollectionCentreManager;
	}

	@Override
	protected void initController() throws Exception {
		
	}

	public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response)
	throws ApplicationException {
		if(!ConfigUtil.getInstance().getIsOpenFrontOrder()){
			//如果没有开启前台下订单功能。
			return new ModelAndView("cart/checkoutUnAvailable");
		}
		
		Shoppingcart shoppingcart = ShoppingCartUtil.getInstance().getCurrentUserShoppingcart();
		if (shoppingcart.getItemsCount() < 1) {
			return new ModelAndView("cart/emptyShoppingcart");
		}
		
		//如果没登录，跳转到登录页
		if (RequestContext.isAnonymousUser()) {
			String type = request.getParameter("type");
			if (!"anonymous".equalsIgnoreCase(type)) {
				request.getSession().setAttribute(CheckoutConstants.TOCHECKOUT, Boolean.TRUE);
				return new ModelAndView(new RedirectView("login.html?fromCheckout=1"));
			}
		}
		
		//是否低于最低采购金额
		if (shoppingcart.isBelowMinimumPurchaseAmount()) {
			return new ModelAndView(new RedirectView("cart/shoppingcart.html"));
		}

		//总金额不能超过8位
		if (shoppingcart.getTotal().compareTo(new BigDecimal("99999999"))==1) {
			return new ModelAndView(new RedirectView("cart/shoppingcart.html?tooLarge=1"));
		}
		
		//验证购物车数据是否被删除
		shoppingcart = checkoutService.validationDeleted(request, response, shoppingcart);
		request.setAttribute("shoppingcart", shoppingcart);
		
		//将获赠的优惠券
		PromoRule promoRule = promoService.getCouponType(shoppingcart.getGainedCouponTypeId());
		request.setAttribute("coupone", promoRule);
		
		CheckoutSession checkoutSession = new CheckoutSession(shoppingcart);
		request.setAttribute("checkoutSession", checkoutSession);
		
		
		//读取地址
		if (!RequestContext.isAnonymousUser()) {
			//用会员的默认地址来填充收货人信息。(若会员非第一次下单，最近一次订单的地址信将会覆盖默认地址，具体参看checkoutSession.setSalesOrder()方法)
			Address address = customerService.getDefShippingAddr(RequestContext.getCurrentUserId());
			checkoutSession.setAddress(address);
			
			List<Address> addressList = customerService.getAllShippingAddressByAppuserId(RequestContext.getCurrentUserId());
			request.setAttribute("addressList", addressList);
		}
		
		//用最近一次的订单信息来预填充
		if (!RequestContext.isAnonymousUser()) {
			SalesOrder salesOrder = salesOrderManager.getLastSalesOrder(RequestContext.getCurrentUserId());
			if (salesOrder != null) {
				checkoutSession.setSalesOrder(salesOrder);
			}
		}
		
		//读取用户积分
		if (!RequestContext.isAnonymousUser()) {
			ShopPoint shopPoint = customerService.getByAppUserId(RequestContext.getCurrentUserId()).getShopPoint();
			if (shopPoint != null) {
				checkoutSession.setAvailableShopPoints(shopPoint.getTotal());	
			} else {
				checkoutSession.setAvailableShopPoints(0);
			}
		}
		
		//读取包装方式
		List<Wrap> wrapList =  checkoutService.getSystemWraps();
		request.setAttribute("wrapList", wrapList);
		
		//读取在线支付信息
		List<PaymentMethod> onlinePaymentMethods = paymentMethodManager.getByPaymentMethodTypeStatus(PaymentMethod.PAYMENT_METHOD_TYPE_ONLINE, Constants.STATUS_ACTIVE);
		request.setAttribute("onlinePaymentMethods", onlinePaymentMethods);
		
		//读取系统默认的支付信息
		List<PaymentMethod> defPaymentMethods = paymentMethodManager.getByPaymentMethodTypeStatus(PaymentMethod.PAYMENT_METHOD_TYPE_OFFLINE, Constants.STATUS_ACTIVE);
		if (defPaymentMethods != null) {
			for (PaymentMethod paymentMethod: defPaymentMethods) {
				request.setAttribute("paymentMethod" + paymentMethod.getPaymentMethodId(), paymentMethod);
				if(checkoutSession.getDefaultPaymentMethodId() == null){
					checkoutSession.setDefaultPaymentMethodId(paymentMethod.getPaymentMethodId());
				}
			}
		}
		
		//提货点数据
		List<SelfCollectionCentre> selfCollectionCentreList = selfCollectionCentreManager.findActiveSelfCollectionCentres();
		request.setAttribute("selfCollectionCentreList", selfCollectionCentreList);
		//提货时间列表
		List<Date> selfCollectDateList = new ArrayList();
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 0));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 1));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 2));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 3));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 4));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 5));
		selfCollectDateList.add(DateUtil.getAddDay(new Date(), 6));
		
		request.setAttribute("selfCollectDateList", selfCollectDateList);
		
		
		return new ModelAndView("cart/onePageCheckout");
	}
	
	//结账成功后跳转到提示页面
	public ModelAndView checkoutSucc(HttpServletRequest request, HttpServletResponse response) {
		//根据订单号重新查询订单传回给页面,注意，当匿名下单时customerId就为空。所以不能使用orderService.getSalesOrderByOrderNo4Safety方法
		String orderNo = request.getParameter("orderNo");
		SalesOrder salesOrder = salesOrderManager.getSalesOrderByOrderNo(orderNo);
		request.setAttribute("salesOrder", salesOrder);
				
		List onlinePaymentMethods = paymentMethodManager.getByPaymentMethodTypeStatus(PaymentMethod.PAYMENT_METHOD_TYPE_ONLINE, Constants.STATUS_ACTIVE);
		request.setAttribute("onlinePaymentMethods", onlinePaymentMethods);
		return new ModelAndView("cart/orderReview");
	}

	//结账后进行在线支付(选择支付网关)
	public ModelAndView selectOnlinePayment(HttpServletRequest request, HttpServletResponse response) {
		String orderNo = request.getParameter("orderNo");
		request.setAttribute("orderNo", orderNo);
		
		String paymentMethodId = request.getParameter("paymentMethodId");
		request.setAttribute("paymentMethodId", paymentMethodId);
		
		List onlinePaymentMethods = paymentMethodManager.getByPaymentMethodTypeStatus(PaymentMethod.PAYMENT_METHOD_TYPE_ONLINE, Constants.STATUS_ACTIVE);
		request.setAttribute("onlinePaymentMethods", onlinePaymentMethods);
		
		return new ModelAndView("cart/checkoutSelectOnlinePayment");
	}
	
	//结账后进行在线支付(进入具体的支付网关)
	public ModelAndView gotoPaymentGateway(HttpServletRequest request, HttpServletResponse response) {
		// 如果是Trial版本，本方法将不会被执行，下面的注释不要删
		// @TRIAL_NOT_SUPPORT@
		String orderNo = request.getParameter("orderNo");
		PaymentMethod paymentMethod = null;
		String strPaymentMethod = request.getParameter("paymentMethodId");
		if (!strPaymentMethod.equals("")) {
			Integer paymentMethodId = new Integer(strPaymentMethod);
			paymentMethod = this.systemService.getPaymentMethod(paymentMethodId);
		}

		if (!orderNo.equals("") && paymentMethod != null) {
			if (paymentMethod.getPaymentMethodType().equals(PaymentMethod.PAYMENT_METHOD_TYPE_ONLINE)) {// 判断是线上支付还是线下支付
				SalesOrder salesOrder = salesOrderManager.getSalesOrderByOrderNo(orderNo);
				PaymentGateway paymentGateway = paymentMethod.getPaymentGateway();
				if (paymentGateway != null) {
					//跳转到支付网关
					request.setAttribute("paymentGateway", paymentGateway);
					request.setAttribute("paymentMethodId", RequestUtil.getParameterNullSafe(request, "paymentMethodId"));
					return new ModelAndView("system/" + paymentGateway.getProcessorFile(), "salesOrder", salesOrder);
				}
					
			}
		}
		logger.warn("goto payment gateway error");
		try {
			response.sendRedirect(request.getContextPath() + "/");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 渲染地区
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView renderRegion(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/cart/include/regionLinkageSelectorForCheckout");
		mv.addObject("regionId",request.getParameter("regionId"));
		return mv;
	}

}